﻿using System;
using AutoMapper;
using Portal.Core.Adapters;
using Portal.Logic.Models;
using Portal.Model;
using Portal.Presentation.Models;

namespace Portal.Presentation.Converters
{
	/// <summary>
	/// Class <see cref="UserViewModelConverter"/> define UserViewModel converter
	/// </summary>
	public class UserViewModelConverter : IUserViewModelConverter
	{
		#region Fields
		private readonly IUserAdapter _adapter;
		#endregion

		#region .ctor
		/// <summary>
		/// Initializes a new instance of the <see cref="UserViewModelConverter"/> class.
		/// </summary>
		/// <param name="adapter">The adapter.</param>
		/// <exception cref="System.ArgumentNullException">adapter</exception>
		public UserViewModelConverter(IUserAdapter adapter)
		{
			if (adapter == null)
			{
				throw new ArgumentNullException("adapter");
			}
			_adapter = adapter;
		}
		#endregion

		#region Methods
		/// <summary>
		/// To the view model.
		/// </summary>
		/// <param name="userInfo">The user information.</param>
		/// <returns></returns>
		public UserInfoDataModel ToModel(IUserInfo userInfo)
		{
			if (userInfo == null)
			{
				return null;
			}

			var model = userInfo.MapNew<IUserInfo, UserInfoDataModel>();
			_adapter.Initialize(userInfo.User);
			model.FullName = _adapter.FullName;
			return model;
		}

		/// <summary>
		/// Converts to IUserInfo.
		/// </summary>
		/// <param name="model">The model.</param>
		/// <param name="user">The user.</param>
		/// <returns>User info.</returns>
		public IUserInfo ToUserInfo(UserInfoDataModel model, IUser user)
		{
			var info = new UserInfo();
			if (model != null)
			{
				model.MapUpdate(user);
				info.PrimaryEmail = MapContactInfo(model.PrimaryEmail, true, ContactInfoType.Email);
				info.SecondaryEmail = MapContactInfo(model.SecondaryEmail, false, ContactInfoType.Email);
				info.PrimaryPhone = MapContactInfo(model.PrimaryPhone, true, ContactInfoType.Phone);
				info.SecondaryPhone = MapContactInfo(model.SecondaryPhone, false, ContactInfoType.Phone);
			}
			info.User = user;
			return info;
		}

		private IContactInfo MapContactInfo(string value, bool isDefault, ContactInfoType type)
		{
			if (string.IsNullOrWhiteSpace(value))
			{
				return null;
			}
			var info = value.MapNew<string, IContactInfo>();
			info.IsDefault = isDefault;
			info.Type = type;
			return info;
		}
		#endregion
	}
}